package com.atguigu.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.atguigu.commonutils.R;
import com.atguigu.vod.service.VodService;
import com.atguigu.vod.utils.InitObject;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/eduvod/video")
@CrossOrigin
public class VodController {
    VodService vodService;
    @Autowired
    public void setVodService(VodService vodService) {
        this.vodService = vodService;
    }

    // 上传视频
    @PostMapping("/uploadAliyunVideo")
    public R uploadVideo(MultipartFile file){
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    // 删除视频
    @DeleteMapping("/{videoId}")
    public R deleteVideoById(@PathVariable String videoId){
        if(vodService.deleteAliyunVideo(videoId)){
            return R.ok().message("删除视频成功!");
        };
        return R.error().code(20001).message("删除视频失败,不存在对应的视频id.");
    }

    // 删除多个视频
    @DeleteMapping("/delete-batch")
    @ApiParam(name = "videoIdList", value = "云端视频id", required = true)
    public R deleteVideoList(@RequestParam("videoList") List videoList){
        vodService.deleteVideoList(videoList);
        return R.ok();
    }

    // 根据视频id来获取视频播放凭证
    @GetMapping("/getPlayAuth/{videoSourcesId}")
    public R getPlayAuth(@PathVariable String videoSourcesId){
        try{
            //初始化参数
            DefaultAcsClient client = InitObject.initVodClient("LTAI5tE8EZyuy17eSNWkLnjp", "CuMB0QZYUQfBWxvtVvHCwT0CPazPeR");
            GetVideoPlayAuthResponse response;
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(videoSourcesId);
            //设置凭证有效时间,单位S
            request.setAuthInfoTimeout(200L);
            response = client.getAcsResponse(request);
            //返回播放凭证
            return R.ok().data("playAuth",response.getPlayAuth());
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.error();
    }
}
